package cn.ibizlab.util.helper.typehandler;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.handlers.AbstractJsonTypeHandler;
import org.apache.ibatis.type.JdbcType;
import java.nio.charset.StandardCharsets;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * bytes转string
 *
 */
public class ByteArrayToStringTypeHandler extends AbstractJsonTypeHandler<String> {

  public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
    ps.setBytes(i, toJson(parameter).getBytes(StandardCharsets.UTF_8));
  }

  public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
    byte bytes[] = rs.getBytes(columnName);
    return ObjectUtils.isEmpty(bytes) ? null : this.parse(new String(bytes, StandardCharsets.UTF_8));
  }

  public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
    String json = rs.getString(columnIndex);
    return StringUtils.isBlank(json) ? null : this.parse(json);
  }

  @Override
  protected String parse(String json) {
    return json;
  }

  @Override
  protected String toJson(String obj) {
    return obj;
  }
}